package com.qijian.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.qijian.common.core.domain.model.LoginUser;
import com.qijian.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 处理新增和更新的基础数据填充，配合BaseEntity和MyBatisPlusConfig使用
 */
@Component
public class MetaHandler implements MetaObjectHandler {

    private static final Logger logger = LoggerFactory.getLogger(MetaHandler.class);

    /**
     * 新增数据执行
     *
     * @param metaObject /
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        //系统方法不需要登陆，且需要覆盖系统变量：createBy,createTime,updateBy,updateTime
        //暂且判定，如果获取不到登陆用户信息，则认为是系统方法，可以修改系统变量
        boolean isCanEdit = false;
        String nickName = "系统";
        try {
            LoginUser userEntity = SecurityUtils.getLoginUser();
            nickName = userEntity.getUser().getNickName();
        } catch (Exception e) {
//            logger.error("用户信息查询失败");
            isCanEdit = true;
        }
        if (!isCanEdit) {
            //部分实体类允许修改系统变量数据
            String className = metaObject.getOriginalObject().getClass().getSimpleName();
            switch (className) {
                case "Item":
                case "Bom":
                case "BomDetail":
                case "LineProcessItem":
                case "Project":
                case "FlowableData":
                    isCanEdit = true;
                    break;
            }
        }
        if (!isCanEdit || this.getFieldValByName("createBy", metaObject) == null)
            this.setFieldValByName("createBy", nickName, metaObject);
        if (!isCanEdit || this.getFieldValByName("createTime", metaObject) == null)
            this.setFieldValByName("createTime", new Date(), metaObject);
        if (!isCanEdit || this.getFieldValByName("updateBy", metaObject) == null)
            this.setFieldValByName("updateBy", nickName, metaObject);
        if (!isCanEdit || this.getFieldValByName("updateTime", metaObject) == null)
            this.setFieldValByName("updateTime", new Date(), metaObject);


    }

    /**
     * 更新数据执行
     *
     * @param metaObject /
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        String nickName = "系统";
        try {
            LoginUser userEntity = SecurityUtils.getLoginUser();
            nickName = userEntity.getUser().getNickName();
        } catch (Exception e) {
//            logger.error("用户信息查询失败");
        }
        this.setFieldValByName("updateTime", new Date(), metaObject);
        this.setFieldValByName("updateBy", nickName, metaObject);
    }

}